package org.academiadecodigo.carcrash.field;

import org.academiadecodigo.carcrash.Utils;

public class Position {

    private int col;
    private int row;

    public Position() {
        this.col = Utils.randInt(0, Field.width);
        this.row = Utils.randInt(0, Field.height);
    }

    public int getCol() {
        return this.col;
    }

    public int getRow() {
        return this.row;
    }

    public void moveTo(int col, int row) {
        this.col = Math.max(0, Math.min(Field.width-1, col));
        this.row = Math.max(0, Math.min(Field.height-1, row));
    }

    public void turn() {
        turn(Direction.values()[Utils.randInt(0, Direction.values().length-1)]);
    }

    public Direction turn(Direction direction) {
        move(direction, 0);
        return direction;
    }

    public void move(int steps) {
        move(Direction.values()[Utils.randInt(0, Direction.values().length-1)], steps);
    }

    public void move(Direction direction, int steps) {
        switch (direction) {
            case UP:
                moveTo(this.col, this.row + steps);
                break;
            case DOWN:
                moveTo(this.col, this.row - steps);
                break;
            case LEFT:
                moveTo(this.col - steps, this.row);
                break;
            case RIGHT:
                moveTo(this.col + steps, this.row);
                break;
            default:
                moveTo(this.col, this.row);
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Position)) {
            return false;
        }
        Position pos = (Position) obj;
        return this.getRow() == pos.getRow() && this.getCol() == pos.getCol();
    }

    @Override
    public String toString() {
        return "(" + this.getCol() + ", " + this.getRow() + ")";
    }

    public Direction getClosestToDirection(Position dest, Direction current) {
        int horizontalDif = Math.abs(this.getCol() - dest.getCol());
        int verticalDif = Math.abs(this.getRow() - dest.getRow());
        if (verticalDif < horizontalDif && verticalDif != 0) {
            if (this.getRow() > dest.getRow()) {
                return Direction.DOWN;
            } else if (this.getRow() < dest.getRow()) {
                return Direction.UP;
            }
        } else if (horizontalDif != 0) {
            if (this.getCol() > dest.getCol()) {
                return Direction.LEFT;
            } else if (this.getCol() < dest.getCol()) {
                return Direction.RIGHT;
            }
        }
        return current;
    }
}
